package com.studyyang.springbootmq.producer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.tools.json.JSONUtil;
import com.studyyang.springbootmq.entity.Employee;
import com.studyyang.springbootmq.entity.constant.RabbitMqProducerConstant;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author yangjin
 * @Description 消息生产者
 * @Date 2021/11/1/22:06
 **/
@Component
public class MessageProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    //添加消息确认监听器
    RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        /**
         * 消息的确认
         * @param correlationData 消息的附加信息
         * @param isAck ture-消息被mq（broker）接收成功，true-消息被mq拒收
         * @param cause 如果拒收，cause则说明拒收的原因，帮助我们对消息的后续处理
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean isAck, String cause) {
            System.out.println("===================消息确认=================");
            System.out.println(correlationData);
            System.out.println(isAck);
            if (!isAck){
                System.err.println(cause);
            }
            System.out.println("===================确认结束=================");
        }
    };

    public void sendMessage(Employee emp){

        //CorrelationData作为消息的附加信息进行传递，通常作为用来保存消息的自定义id
        CorrelationData cld = new CorrelationData(emp.getEmpNo() + "_" + System.currentTimeMillis());
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.convertAndSend(RabbitMqProducerConstant.EXCHANGE_MESSAGE_SENDER,"hr.employee", emp,cld);

    }
}
